<?php

class IndexController extends Controller
{
    public function actionIndex()
    {
        $this->render('index',array(
            'userName'=>Yii::app()->user->name,
        ));
    }

    public function actionLogin()
    {
        $user=Yii::app()->user->model;

        $user->setScenario('login');
        $this->performAjaxValidation($user);

        if(isset($_POST['Customer'])){
            $identity=new UserIdentity($_POST['Customer']['email'], $_POST['Customer']['password']);

            if($identity->login()){
                Yii::app()->notification->message=Yii::t('account/index','helloUser',array('{user}'=>Yii::app()->user->name));
                $this->redirect(Yii::app()->createUrl('account/index',array()));
            }else{
                Yii::app()->notification->error=$identity->errorCode;
                $this->redirect(Yii::app()->homeUrl);
            }
        }else{
            $this->redirect(Yii::app()->homeUrl);
        }
    }

    public function actionRegister()
    {
        $user=Yii::app()->user->model;
        $user->setScenario('register');

        $this->performAjaxValidation($user);

        if(isset($_POST['Customer'])){
            $identity=new UserIdentity($_POST['Customer']['email'], $_POST['Customer']['password']);

            if($identity->register($_POST['Customer'])){
                Yii::app()->notification->message=Yii::t('account/index','helloUser',array('{user}'=>Yii::app()->user->name));
            }else{
                Yii::app()->notification->error=$identity->error;
                $this->redirect(Yii::app()->homeUrl);
            }
            $this->redirect(Yii::app()->createUrl('account/index'));
        }else{
            $this->render('login',array());
        }
    }

    public function actionLogout()
    {
        $name=Yii::app()->user->name;
        Yii::app()->user->logout();
        Yii::app()->notification->message=Yii::t('account/index','byUser',array('{user}'=>$name));
        $this->redirect(Yii::app()->homeUrl);
    }

    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && ($_POST['ajax']==='login-form' || $_POST['ajax']==='register-form')){
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actions()
    {
        return array(
            'captcha'=>array(
                'class'=>'CCaptchaAction',
            ),
        );
    }
}